package com.app.reportproblem;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.Scope;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.model.people.Person;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class LoginGoogleActivity extends FragmentActivity implements
		GoogleApiClient.ConnectionCallbacks,
		GoogleApiClient.OnConnectionFailedListener {

	private GoogleApiClient mGoogleApiClient;
	private ConnectionResult mConnectionResult;
	private ProgressDialog mConnectionProgressDialog;
	private static final int RC_SIGN_IN = 0;
	private boolean mSignInClicked;
	private boolean mIntentInProgress;

	public static int REQUEST_CODE_RESOLVE_ERR = 100;
	
    private static final String CLIENT_ID = "997459520096-lq7ac506f4ncked6i47ta849i1uu1v82.apps.googleusercontent.com";
    final private List<String> SCOPES = Arrays.asList(new String[]{
	    "googleapis.com/auth/plus"
	});

	public LoginGoogleActivity() {
	}

	public GoogleApiClient getGoogleApiClient() {
		return mGoogleApiClient;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		View v = new View(this);
		v.setBackgroundColor(getResources().getColor(android.R.color.transparent));
		setContentView(v);
		mGoogleApiClient = new GoogleApiClient.Builder(this)
				.addConnectionCallbacks(this)
				.addOnConnectionFailedListener(this).addApi(Plus.API, null)
				.addScope(Plus.SCOPE_PLUS_LOGIN).build();

		// Progress bar to be displayed if the connection failure is not
		// resolved.
		mConnectionProgressDialog = new ProgressDialog(this);
		mConnectionProgressDialog.setMessage("Signing in...");
	}
	
	Handler mHandler = new Handler();

	@Override
	protected void onStart() {
		super.onStart();
		if (mGoogleApiClient != null) {
			mGoogleApiClient.connect();
			mHandler.postDelayed(new Runnable() {
				
				@Override
				public void run() {
					signInWithGplus();
				}
			}, 1000);
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
		if (mGoogleApiClient != null) {
			if (mGoogleApiClient.isConnected()) {
				mGoogleApiClient.disconnect();
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int responseCode,
			Intent intent) {
		super.onActivityResult(requestCode, responseCode, intent);
		if (requestCode == RC_SIGN_IN) {
			if (responseCode != RESULT_OK) {
				mSignInClicked = false;
			}

			mIntentInProgress = false;

			if (!mGoogleApiClient.isConnecting()) {
				mGoogleApiClient.connect();
			}
		}

	}

	@Override
	public void onConnectionFailed(ConnectionResult result) {
		if (!result.hasResolution()) {
			GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
					0).show();
			return;
		}

		if (!mIntentInProgress) {
			// Store the ConnectionResult for later usage
			mConnectionResult = result;

			if (mSignInClicked) {
				// The user has already clicked 'sign-in' so we attempt to
				// resolve all
				// errors until the user is signed in, or they cancel.
				resolveSignInError();
			}
		}

	}

	@Override
	public void onConnected(Bundle connectionHint) {
		mConnectionProgressDialog.dismiss();
		getTokenAccess();
		Toast.makeText(this, "Login success", Toast.LENGTH_SHORT).show();
		/*
		Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
		
		final String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
		
		Thread th = new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					String token = GoogleAuthUtil.getToken(LoginGoogleActivity.this, email, Plus.SCOPE_PLUS_LOGIN.toString());
					Log.i("DATA", "ACCESS_TOKEN: "+token);
				} catch (UserRecoverableAuthException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (GoogleAuthException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		th.start();
			
		*/

	}
	
	public void getTokenAccess() {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
					final String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
					try {
						String scope = String.format("oauth2:server:client_id:%s:api_scope:%s", CLIENT_ID, TextUtils.join(" ", SCOPES));
						String token = GoogleAuthUtil.getToken(LoginGoogleActivity.this, email, "googleapis.com/auth/plus");
						Log.e("TOKEN", token);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	@Override
	public void onConnectionSuspended(int cause) {

	}
	
	private void resolveSignInError() {
		if (mConnectionResult!=null && mConnectionResult.hasResolution()) {
			try {
				mIntentInProgress = true;
				mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
			} catch (SendIntentException e) {
				mIntentInProgress = false;
				mGoogleApiClient.connect();
			}
		}
	}
	
	private void signInWithGplus() {
		if (!mGoogleApiClient.isConnecting()) {
			mSignInClicked = true;
			resolveSignInError();
		}
	}
}
